package pro.shuangxi.auth.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：mengshx
 * @date ：Created in 2022/8/14 11:45
 * @description：jwt
 */
public class JwtUtils {
    public static String generateToken(Map<String, String> claims){
        JWTCreator.Builder builder = JWT.create();
        for (Map.Entry<String, String> entry : claims.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }
        Date now = new Date();
        builder.withExpiresAt(DateUtils.addDays(now, 7));
        return  builder.sign(Algorithm.HMAC256("@@mengshuangxi"));
    }
    public static Map<String, String>  analysis(String token){
        Verification verification = JWT.require(Algorithm.HMAC256("@@mengshuangxi"));
        JWTVerifier verifier = verification.build();
        DecodedJWT decodedJWT = verifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        Map<String, String> resp = new HashMap<>();
        for (Map.Entry<String, Claim> entry : claims.entrySet()) {
            resp.put(entry.getKey(), entry.getValue().asString());
        }
        return resp;
    }
    public static boolean  isExpires(String token){
        Verification verification = JWT.require(Algorithm.HMAC256("@@mengshuangxi"));
        JWTVerifier verifier = verification.build();
        DecodedJWT decodedJWT = verifier.verify(token);
        Date expiresAt = decodedJWT.getExpiresAt();
        return expiresAt.getTime() < new Date().getTime();
    }
}
